import {
  ArgumentsHost,
  Catch,
  ExceptionFilter,
  HttpException,
  HttpStatus,
  Logger,
} from '@nestjs/common';
import { formatDate } from '../utils/index';

@Catch()
export class HttpExceptionFilter<T> implements ExceptionFilter {
  catch(exception: T, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    Logger.log(exception, '错误提示');
    const errorResponse = {
      status,
      message: (exception as any).message,
      code: 1, // 错误码
      path: request.url, // 错误url地址
      method: request.method, // 请求方法
      timestamp: new Date().toISOString(), // 错误时间
    };
    Logger.error(
      `[${formatDate(Date.now())} ${request.method} ${request.url}]`,
      JSON.stringify(errorResponse),
      'HttpExceptionFilter',
    );

    response.status(status);
    response.header('Content-type', 'application/json; charset=utf-8');
    response.send(errorResponse);
  }
}
